import random

from flask import request, jsonify, session, redirect, url_for, make_response
from werkzeug.security import generate_password_hash, check_password_hash

from models import db
from models.index import Follow
from models.index import User
from . import passport_blu


# 注册
@passport_blu.route('/passport/register', methods=['GET', 'POST'])
def register():
    mobile = request.json.get('mobile')  # 用户名
    password = request.json.get('password')  # 密码
    image_code = request.json.get('image_code')  # 验证码
    smscode = request.json.get('smscode')  # 短信验证码
    #
    # print(mobile,password,image_code,smscode)
    #
    # return '成功'

    if session.get('image_code').lower() != image_code.lower():
        ret = {

            'erro': 1003,
            'errmsg': '重新输入验证码'
        }
        return jsonify(ret)

    if db.session.query(User).filter(User.mobile == mobile).first():
        return jsonify({
            "errno": 1001,
            "errmsg": "已经注册..."
        })

    user = User()
    user.nick_name = mobile
    user.password_hash = generate_password_hash(password)
    user.mobile = mobile
    try:
        db.session.add(user)
        db.session.commit()

        session['user_id'] = user.id
        session['nick_name'] = mobile

        ret = {
            "errno": 0,
            "errmsg": "注册成功..."
        }
    except Exception as ret:
        print("---->", ret)
        db.session.rollback()  # 如果在将用户的信
        ret = {
            "errno": 1002,
            "errmsg": "注册失败..."
        }
    return jsonify(ret)


# 登陆
@passport_blu.route("/passport/login", methods=["GET", "POST"])
def login():
    mobile = request.json.get('mobile')  # 用户名
    password = request.json.get('password')  # 密码

    user = db.session.query(User).filter(User.mobile == mobile).first()
    if user and check_password_hash(user.password_hash, password):
        ret = {
            "errno": 0,
            "errmsg": "登录成功"
        }

        session['user_id'] = user.id
        session['nick_name'] = mobile
    else:
        ret = {
            "errno": 2001,
            "errmsg": "用户名或者密码错误"
        }

    return jsonify(ret)


# 验证码
@passport_blu.route('/passport/image_code')
def image_code():
    # with open('./yanzhengma.png', 'rb') as f:
    #     image = f.read()

    from utils.captcha.captcha import captcha

    # 生成验证码
    # hash值  验证码值  图片内容
    name, text, image = captcha.generate_captcha()

    print("刚刚生成的验证码：", text)

    session['image_code'] = text
    resp = make_response(image)

    resp.headers['Content-type'] = 'image/png'

    return resp


# 关注
@passport_blu.route('/user/follow', methods=['GET', 'POST'])
def follow():
    # 1. 提取当前用户的信息
    user_id = session.get("user_id")

    # 2. 作者的信息（id）
    author_id = request.json.get("user_id")
    action = request.json.get("action")

    # 3. 逻辑判断（用户是否登录，用户是否关注过。。。）
    if not all([author_id, action]):
        ret = {
            "errno": 3001,
            "errmsg": "缺少必要的参数"
        }
        return jsonify(ret)

    if not user_id:
        ret = {
            "errno": 3002,
            "errmsg": "未登录"
        }
        return jsonify(ret)

    # 4. 判断用户要进行的是关注、还是取消关注功能
    if action == "do":
        # 关注
        author = db.session.query(User).filter(User.id == author_id).first()
        if user_id in [x.id for x in author.followers]:
            ret = {
                "errno": 3003,
                "errmsg": "已关注，请勿重复关注"
            }
            return jsonify(ret)

        # . 保存到数据库
        try:
            follow = Follow(followed_id=author_id, follower_id=user_id)
            db.session.add(follow)
            db.session.commit()
            ret = {
                "errno": 0,
                "errmsg": "关注成功"
            }

            return jsonify(ret)
        except Exception as ret:
            db.session.rollback()
            ret = {
                "errno": 3004,
                "errmsg": "关注失败..."
            }

            return jsonify(ret)
    elif action == "undo":
        # 取消关注
        try:
            print("----------1----------")
            # follow = Follow(followed_id=author_id, follower_id=user_id)
            follow = db.session.query(Follow).filter(Follow.followed_id == author_id,
                                                     Follow.follower_id == user_id).first()
            print(follow)
            print("----------1-1---------")
            db.session.delete(follow)
            print("----------1-2---------")
            db.session.commit()
            print("----------1-3---------")
            ret = {
                "errno": 0,
                "errmsg": "取消关注成功"
            }
            print("----------1-4---------")

            return jsonify(ret)
        except Exception as ret:
            print("----------2----------", ret)
            db.session.rollback()
            ret = {
                "errno": 3005,
                "errmsg": "取消关注失败..."
            }
            return jsonify(ret)


# 退出
@passport_blu.route("/passport/logout")
def logout():
    # 清空登录状态
    session.clear()

    return redirect(url_for('index_blu.index'))


@passport_blu.route("/passport/smscode", methods=["POST"])
def smscode():
    # 1. 提取数据
    image_code = request.json.get("image_code")
    mobile = request.json.get("mobile")

    # 2. 校验图片验证码是否正确
    image_code_session = session.get("image_code")
    print("输入的验证码", image_code)
    print("生成的验证码", image_code_session)
    if mobile != session.get('mobile'):
        ret = {
            "errno": 4003,
            "errmsg": "手机号码错误"
        }
        return jsonify(ret)

    if image_code.lower() != image_code_session.lower():
        ret = {
            "errno": 4004,
            "errmsg": "图片验证码错误..."
        }
        return jsonify(ret)

    # 3. 生成一个随机的6位数
    sms_code = str(random.randint(100000, 999999))
    print("短信验证码是:", sms_code)

    # 4. 存储到session中
    session['sms_code'] = sms_code
    session['mobile'] = mobile

    # 5. 通过短信发送这个6位数
    # send_msg_to_phone(mobile, sms_code)

    ret = {
        "errno": 0,
        "errmsg": "发送短信验证码成功..."
    }

    return jsonify(ret)
